<template>
  <div class="exam-container">
    <!-- 顶部导航 -->
    <div class="exam-header">
      <div class="header-content">
        <h1>在线考试</h1>
        <p>智能组卷，实时评分，全面检验学习成果</p>
        
        <div class="exam-stats">
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><EditPen /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ examStats.totalExams }}</div>
              <div class="stat-label">可用考试</div>
            </div>
          </div>
          
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><Trophy /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ examStats.completedExams }}</div>
              <div class="stat-label">已完成</div>
            </div>
          </div>
          
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><Star /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-number">{{ examStats.averageScore }}</div>
              <div class="stat-label">平均分</div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 筛选和搜索 -->
    <div class="filter-section">
      <div class="filter-content">
        <div class="search-bar">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索考试名称、科目..."
            clearable
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
        
        <div class="filter-controls">
          <el-select v-model="subjectFilter" placeholder="选择科目" clearable>
            <el-option 
              v-for="subject in subjects" 
              :key="subject.value"
              :label="subject.label" 
              :value="subject.value" 
            />
          </el-select>
          
          <el-select v-model="difficultyFilter" placeholder="难度等级" clearable>
            <el-option label="简单" value="easy" />
            <el-option label="中等" value="medium" />
            <el-option label="困难" value="hard" />
          </el-select>
          
          <el-select v-model="statusFilter" placeholder="考试状态" clearable>
            <el-option label="未开始" value="not_started" />
            <el-option label="进行中" value="in_progress" />
            <el-option label="已完成" value="completed" />
            <el-option label="已过期" value="expired" />
          </el-select>
        </div>
      </div>
    </div>

    <!-- 考试分类标签 -->
    <div class="category-tabs">
      <div class="tabs-container">
        <div 
          v-for="category in examCategories" 
          :key="category.key"
          class="category-tab"
          :class="{ active: activeCategory === category.key }"
          @click="activeCategory = category.key"
        >
          <el-icon><component :is="category.icon" /></el-icon>
          <span>{{ category.label }}</span>
          <el-badge :value="category.count" v-if="category.count > 0" />
        </div>
      </div>
    </div>

    <!-- 考试列表 -->
    <div class="exam-list-section">
      <div class="section-header">
        <h2>{{ getCategoryTitle() }}</h2>
        <div class="header-actions">
          <el-button @click="createExam">
            <el-icon><Plus /></el-icon>
            创建考试
          </el-button>
        </div>
      </div>

      <div class="exam-grid">
        <div 
          v-for="exam in filteredExams" 
          :key="exam.id"
          class="exam-card"
          :class="getExamCardClass(exam)"
        >
          <div class="exam-header">
            <div class="exam-subject">{{ exam.subject }}</div>
            <div class="exam-status">
              <el-tag :type="getStatusType(exam.status)">
                {{ getStatusText(exam.status) }}
              </el-tag>
            </div>
          </div>
          
          <div class="exam-content">
            <h3>{{ exam.title }}</h3>
            <p class="exam-description">{{ exam.description }}</p>
            
            <div class="exam-meta">
              <div class="meta-item">
                <el-icon><Clock /></el-icon>
                <span>{{ exam.duration }}分钟</span>
              </div>
              <div class="meta-item">
                <el-icon><Document /></el-icon>
                <span>{{ exam.questionCount }}题</span>
              </div>
              <div class="meta-item">
                <el-icon><Star /></el-icon>
                <span>{{ getDifficultyText(exam.difficulty) }}</span>
              </div>
            </div>
            
            <div class="exam-time-info">
              <div class="time-item">
                <span class="label">开始时间：</span>
                <span class="value">{{ formatDateTime(exam.startTime) }}</span>
              </div>
              <div class="time-item">
                <span class="label">结束时间：</span>
                <span class="value">{{ formatDateTime(exam.endTime) }}</span>
              </div>
            </div>
            
            <!-- 考试进度（如果已开始） -->
            <div v-if="exam.progress !== undefined" class="exam-progress">
              <div class="progress-label">
                <span>答题进度</span>
                <span>{{ exam.progress }}%</span>
              </div>
              <el-progress :percentage="exam.progress" :show-text="false" />
            </div>
            
            <!-- 考试成绩（如果已完成） -->
            <div v-if="exam.score !== undefined" class="exam-score">
              <div class="score-display">
                <span class="score-label">考试成绩</span>
                <span class="score-value" :class="getScoreClass(exam.score)">
                  {{ exam.score }}分
                </span>
              </div>
              <div class="score-details">
                <span>正确率：{{ exam.accuracy }}%</span>
                <span>用时：{{ exam.usedTime }}分钟</span>
              </div>
            </div>
          </div>
          
          <div class="exam-actions">
            <template v-if="exam.status === 'not_started'">
              <el-button type="primary" @click="startExam(exam)">
                开始考试
              </el-button>
              <el-button @click="viewExamDetails(exam)">
                查看详情
              </el-button>
            </template>
            
            <template v-else-if="exam.status === 'in_progress'">
              <el-button type="warning" @click="continueExam(exam)">
                继续考试
              </el-button>
              <el-button @click="viewProgress(exam)">
                查看进度
              </el-button>
            </template>
            
            <template v-else-if="exam.status === 'completed'">
              <el-button type="success" @click="viewResult(exam)">
                查看成绩
              </el-button>
              <el-button @click="reviewExam(exam)">
                错题回顾
              </el-button>
            </template>
            
            <template v-else-if="exam.status === 'expired'">
              <el-button disabled>已过期</el-button>
            </template>
          </div>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="filteredExams.length === 0" class="empty-state">
        <el-empty description="暂无考试数据">
          <el-button type="primary" @click="createExam">创建考试</el-button>
        </el-empty>
      </div>

      <!-- 分页 -->
      <div v-if="filteredExams.length > 0" class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[9, 18, 36]"
          :total="totalExams"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { 
  EditPen, Trophy, Star, Search, Clock, Document, Plus,
  Monitor, Reading, Calculator, Globe
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()

// 响应式数据
const searchKeyword = ref('')
const subjectFilter = ref('')
const difficultyFilter = ref('')
const statusFilter = ref('')
const activeCategory = ref('all')
const currentPage = ref(1)
const pageSize = ref(9)
const totalExams = ref(45)

// 考试统计
const examStats = ref({
  totalExams: 45,
  completedExams: 12,
  averageScore: 85
})

// 科目列表
const subjects = ref([
  { label: '前端开发', value: 'frontend' },
  { label: '后端开发', value: 'backend' },
  { label: '数据库', value: 'database' },
  { label: '算法与数据结构', value: 'algorithm' },
  { label: '计算机网络', value: 'network' },
  { label: '操作系统', value: 'os' }
])

// 考试分类
const examCategories = ref([
  { key: 'all', label: '全部考试', icon: 'Document', count: 45 },
  { key: 'programming', label: '编程考试', icon: 'Monitor', count: 18 },
  { key: 'theory', label: '理论考试', icon: 'Reading', count: 15 },
  { key: 'practice', label: '实践考试', icon: 'Calculator', count: 12 }
])

// 考试列表
const exams = ref([
  {
    id: 1,
    title: 'JavaScript基础知识测试',
    description: '测试JavaScript基础语法、数据类型、函数等核心概念',
    subject: '前端开发',
    category: 'programming',
    difficulty: 'easy',
    duration: 60,
    questionCount: 30,
    status: 'not_started',
    startTime: new Date('2024-01-20 09:00:00'),
    endTime: new Date('2024-01-25 18:00:00')
  },
  {
    id: 2,
    title: 'Vue3组件开发实战',
    description: '考查Vue3组件开发、组合式API、状态管理等高级特性',
    subject: '前端开发',
    category: 'programming',
    difficulty: 'medium',
    duration: 90,
    questionCount: 25,
    status: 'in_progress',
    progress: 65,
    startTime: new Date('2024-01-15 09:00:00'),
    endTime: new Date('2024-01-22 18:00:00')
  },
  {
    id: 3,
    title: 'React高级特性考试',
    description: '深入考查React Hooks、性能优化、状态管理等高级主题',
    subject: '前端开发',
    category: 'programming',
    difficulty: 'hard',
    duration: 120,
    questionCount: 35,
    status: 'completed',
    score: 88,
    accuracy: 85,
    usedTime: 105,
    startTime: new Date('2024-01-10 09:00:00'),
    endTime: new Date('2024-01-15 18:00:00')
  },
  {
    id: 4,
    title: 'Node.js后端开发',
    description: '测试Node.js服务端开发、Express框架、数据库操作等',
    subject: '后端开发',
    category: 'programming',
    difficulty: 'medium',
    duration: 90,
    questionCount: 28,
    status: 'not_started',
    startTime: new Date('2024-01-25 09:00:00'),
    endTime: new Date('2024-01-30 18:00:00')
  },
  {
    id: 5,
    title: '数据结构与算法',
    description: '考查常用数据结构、排序算法、搜索算法等基础知识',
    subject: '算法与数据结构',
    category: 'theory',
    difficulty: 'hard',
    duration: 150,
    questionCount: 40,
    status: 'expired',
    startTime: new Date('2024-01-05 09:00:00'),
    endTime: new Date('2024-01-10 18:00:00')
  }
])

// 计算属性
const filteredExams = computed(() => {
  let filtered = exams.value

  // 分类筛选
  if (activeCategory.value !== 'all') {
    filtered = filtered.filter(exam => exam.category === activeCategory.value)
  }

  // 科目筛选
  if (subjectFilter.value) {
    filtered = filtered.filter(exam => exam.subject === subjectFilter.value)
  }

  // 难度筛选
  if (difficultyFilter.value) {
    filtered = filtered.filter(exam => exam.difficulty === difficultyFilter.value)
  }

  // 状态筛选
  if (statusFilter.value) {
    filtered = filtered.filter(exam => exam.status === statusFilter.value)
  }

  // 搜索筛选
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(exam => 
      exam.title.toLowerCase().includes(keyword) ||
      exam.description.toLowerCase().includes(keyword) ||
      exam.subject.toLowerCase().includes(keyword)
    )
  }

  return filtered
})

// 方法
const getCategoryTitle = () => {
  const category = examCategories.value.find(c => c.key === activeCategory.value)
  return category ? category.label : '全部考试'
}

const getStatusType = (status) => {
  const typeMap = {
    not_started: '',
    in_progress: 'warning',
    completed: 'success',
    expired: 'danger'
  }
  return typeMap[status] || ''
}

const getStatusText = (status) => {
  const textMap = {
    not_started: '未开始',
    in_progress: '进行中',
    completed: '已完成',
    expired: '已过期'
  }
  return textMap[status] || status
}

const getDifficultyText = (difficulty) => {
  const textMap = {
    easy: '简单',
    medium: '中等',
    hard: '困难'
  }
  return textMap[difficulty] || difficulty
}

const getExamCardClass = (exam) => {
  return {
    'exam-not-started': exam.status === 'not_started',
    'exam-in-progress': exam.status === 'in_progress',
    'exam-completed': exam.status === 'completed',
    'exam-expired': exam.status === 'expired'
  }
}

const getScoreClass = (score) => {
  if (score >= 90) return 'score-excellent'
  if (score >= 80) return 'score-good'
  if (score >= 60) return 'score-pass'
  return 'score-fail'
}

const formatDateTime = (date) => {
  return new Date(date).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const handleSearch = () => {
  currentPage.value = 1
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

const handleCurrentChange = (page) => {
  currentPage.value = page
}

// 考试操作
const createExam = () => {
  router.push('/exam/create')
}

const startExam = async (exam) => {
  try {
    await ElMessageBox.confirm(
      `确定要开始考试"${exam.title}"吗？考试开始后不能暂停。`,
      '开始考试',
      {
        confirmButtonText: '开始',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    router.push(`/exam/take/${exam.id}`)
  } catch {
    // 用户取消
  }
}

const continueExam = (exam) => {
  router.push(`/exam/take/${exam.id}`)
}

const viewExamDetails = (exam) => {
  router.push(`/exam/details/${exam.id}`)
}

const viewProgress = (exam) => {
  router.push(`/exam/progress/${exam.id}`)
}

const viewResult = (exam) => {
  router.push(`/exam/result/${exam.id}`)
}

const reviewExam = (exam) => {
  router.push(`/exam/review/${exam.id}`)
}

onMounted(() => {
  // 初始化数据
})
</script>

<style lang="scss" scoped>
.exam-container {
  min-height: 100vh;
  background: var(--el-bg-color-page);
}

.exam-header {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: white;
  padding: 60px 0;
}

.header-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  text-align: center;
  
  h1 {
    font-size: 3rem;
    font-weight: 700;
    margin-bottom: 16px;
  }
  
  p {
    font-size: 1.25rem;
    opacity: 0.9;
    margin-bottom: 40px;
  }
}

.exam-stats {
  display: flex;
  justify-content: center;
  gap: 40px;
  
  @media (max-width: 768px) {
    flex-direction: column;
    align-items: center;
    gap: 20px;
  }
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 16px;
  background: rgba(255, 255, 255, 0.1);
  padding: 20px;
  border-radius: 12px;
  backdrop-filter: blur(10px);
  
  .stat-icon {
    width: 50px;
    height: 50px;
    background: rgba(255, 255, 255, 0.2);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .el-icon {
      font-size: 24px;
    }
  }
  
  .stat-number {
    font-size: 2rem;
    font-weight: 700;
    margin-bottom: 4px;
  }
  
  .stat-label {
    font-size: 0.9rem;
    opacity: 0.8;
  }
}

.filter-section {
  max-width: 1200px;
  margin: 0 auto;
  padding: 30px 20px;
}

.filter-content {
  display: flex;
  gap: 20px;
  align-items: center;
  
  @media (max-width: 768px) {
    flex-direction: column;
    align-items: stretch;
  }
}

.search-bar {
  flex: 1;
  max-width: 400px;
}

.filter-controls {
  display: flex;
  gap: 12px;
  
  @media (max-width: 768px) {
    flex-wrap: wrap;
  }
}

.category-tabs {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px 30px;
}

.tabs-container {
  display: flex;
  gap: 8px;
  overflow-x: auto;
  padding-bottom: 8px;
}

.category-tab {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 20px;
  background: white;
  border: 1px solid var(--el-border-color-lighter);
  border-radius: 25px;
  cursor: pointer;
  transition: all 0.3s ease;
  white-space: nowrap;
  
  &:hover {
    border-color: var(--el-color-primary);
    color: var(--el-color-primary);
  }
  
  &.active {
    background: var(--el-color-primary);
    color: white;
    border-color: var(--el-color-primary);
  }
}

.exam-list-section {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px 40px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  
  h2 {
    font-size: 1.5rem;
    font-weight: 600;
    color: var(--el-text-color-primary);
  }
}

.exam-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 24px;
  margin-bottom: 40px;
}

.exam-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  transition: all 0.3s ease;
  border-left: 4px solid transparent;
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
  }
  
  &.exam-not-started {
    border-left-color: var(--el-color-info);
  }
  
  &.exam-in-progress {
    border-left-color: var(--el-color-warning);
  }
  
  &.exam-completed {
    border-left-color: var(--el-color-success);
  }
  
  &.exam-expired {
    border-left-color: var(--el-color-danger);
    opacity: 0.7;
  }
}

.exam-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  
  .exam-subject {
    font-size: 12px;
    color: var(--el-color-primary);
    background: var(--el-color-primary-light-9);
    padding: 4px 8px;
    border-radius: 4px;
  }
}

.exam-content {
  h3 {
    font-size: 18px;
    font-weight: 600;
    margin-bottom: 8px;
    color: var(--el-text-color-primary);
  }
  
  .exam-description {
    font-size: 14px;
    color: var(--el-text-color-secondary);
    margin-bottom: 16px;
    line-height: 1.5;
  }
}

.exam-meta {
  display: flex;
  gap: 16px;
  margin-bottom: 16px;
  
  .meta-item {
    display: flex;
    align-items: center;
    gap: 4px;
    font-size: 14px;
    color: var(--el-text-color-secondary);
  }
}

.exam-time-info {
  margin-bottom: 16px;
  
  .time-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 4px;
    font-size: 14px;
    
    .label {
      color: var(--el-text-color-secondary);
    }
    
    .value {
      color: var(--el-text-color-primary);
    }
  }
}

.exam-progress {
  margin-bottom: 16px;
  
  .progress-label {
    display: flex;
    justify-content: space-between;
    margin-bottom: 8px;
    font-size: 14px;
    color: var(--el-text-color-primary);
  }
}

.exam-score {
  margin-bottom: 16px;
  
  .score-display {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
    
    .score-label {
      font-size: 14px;
      color: var(--el-text-color-secondary);
    }
    
    .score-value {
      font-size: 24px;
      font-weight: 700;
      
      &.score-excellent {
        color: var(--el-color-success);
      }
      
      &.score-good {
        color: var(--el-color-primary);
      }
      
      &.score-pass {
        color: var(--el-color-warning);
      }
      
      &.score-fail {
        color: var(--el-color-danger);
      }
    }
  }
  
  .score-details {
    display: flex;
    justify-content: space-between;
    font-size: 12px;
    color: var(--el-text-color-placeholder);
  }
}

.exam-actions {
  display: flex;
  gap: 8px;
  
  .el-button {
    flex: 1;
  }
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 40px;
}
</style>
